package com.devicemantra.coordinate.interfaces.call;

import java.io.IOException;
import com.devicemantra.coordinate.dataobjects.*;

import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import sun.misc.Perf;

import com.devicemantra.coordinate.ds.tests.*;
import com.devicemantra.coordinate.util.CLogger;

public class AuthCallTask extends HttpServlet 
{ 
	private String lBaseUrl = "http://www.devicemantra2.appspot.com/";
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
	throws IOException 
	{
		doGet(req,resp);
	}
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
	throws IOException {
	
	CLogger.log("Auth Call task started");
	System.out.println("Auth Call task started");
	String lMobileNumber = req.getParameter("mobile_number");
	String lCallMesgId = req.getParameter("call_responder_id");
	System.out.println("Mob " + lMobileNumber + " lCallMesgId" + lCallMesgId);
	
	System.out.println("Fetching message for AuthMessage id");
	boolean lDoesExist = true;
	PersistenceManager lPMF = PMF.get().getPersistenceManager();
	CAuthMobileMessage lCMessage = null;
	try
	{
		lCMessage = lPMF.getObjectById(CAuthMobileMessage.class,lCallMesgId);
	} catch(JDOObjectNotFoundException e)
	{
		lDoesExist = false;
	}
	
	if(false == lDoesExist) 
	{
		System.out.println("FATAL ERROR: The message id does not exist");
		return;
	}  
	
	String lUrl = lBaseUrl + "/operations/authenticate/caller/AuthMobileUser?" + "id=" + lCallMesgId;
	System.out.println("Url to call for twilio is " + lUrl);
	CMakeCall.makeCallExample(lMobileNumber, lUrl);
	
	}

}
